package com.heima.media.interceptor;

import com.heima.common.dto.User;
import com.heima.common.util.MediaThreadUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    /**
     * 前置拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的用户id
        String userId = request.getHeader("userId");
        //不为空则存放在线程中
        if (userId != null){
            User user = new User();
            user.setUserId(Integer.parseInt(userId));
            MediaThreadUtil.setThread(user);
        }
        return true;
    }

    /*
        后置拦截
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        MediaThreadUtil.delThread();
    }
}
